<template>
  <div class="qr-code-img">
    <img v-if="qrcodeImgUrl" class="qr-code" :src="qrcodeImgUrl" alt="" />
    <img class="qr-code-logo" v-if="logoUrl" :src="logoUrl" alt="logo" />
  </div>
</template>
<script>
import QRCode from 'qrcode'
export default {
  props: {
    url: {
      type: String,
    },
    logoUrl: {
      type: String,
      default: '',
    },
    background: {
      type: String,
      default: '#fff',
    },
  },
  data() {
    return {
      qrcodeImgUrl: '',
    }
  },
  watch: {
    url() {
      this.buildQrImg()
    },
  },
  mounted() {
    this.buildQrImg()
  },
  methods: {
    buildQrImg() {
      if (this.url) {
        QRCode.toDataURL(this.url, {
          color: { light: this.background },
        }).then(url => {
          this.qrcodeImgUrl = url
          this.$emit('rendered', url)
        })
      } else {
        this.qrcodeImgUrl = ''
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.qr-code-img {
  height: 100%;
  width: 100%;
  position: relative;
  .qr-code {
    width: 100%;
  }
  .qr-code-logo {
    width: 20%;
    height: 20%;
    position: absolute;
    left: 40%;
    top: 40%;
    background-color: #ffffff;
  }
}
</style>
